package com.lzp.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.lzp.utils.error.ResponseCode;

import java.io.Serializable;

/**
 * 通用HTTP响应对象
 *
 * @author lzp
 * @date 2020/7/21
 */
public class ServerResponse<T> implements Serializable {

    private int status;  // 状态码

    private String msg;  // 消息

    private T data;      // 数据

    // 构造
    private ServerResponse(int status) {
        this.status = status;
    }

    private ServerResponse(int status, T data) {
        this.status = status;
        this.data = data;
    }

    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    @JsonIgnore
    // 序列化反序列化时用，使之不在json序列化结果当中
    public boolean isSuccess() {  // 字段在序列化之后不会显示在json中
        return this.status == ResponseCode.SUCCESS.getCode();
    }

    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    public static <T> ServerResponse<T> createBySuccess() {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), "OK");
    }

    public static <T> ServerResponse<T> createBySuccessMsg(String msg) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg);
    }

    public static <T> ServerResponse<T> createBySuccess(T data) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data);
    }

    public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg, data);
    }

    public static <T> ServerResponse<T> createByError(ResponseCode responseCode) {
        return new ServerResponse<T>(responseCode.getCode(), responseCode.getMessage());
    }

    public static <T> ServerResponse<T> createByErrorMsg(String errorMsg) {
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(), errorMsg);
    }

    public static <T> ServerResponse<T> createByErrorMap(T data) {
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(), "error", data);
    }

    public static <T> ServerResponse<T> createByErrorMsg(ResponseCode responseCode, String errorMsg) {
        responseCode.setErrorMsg(errorMsg);
        return new ServerResponse<T>(responseCode.getCode(), responseCode.getMessage());
    }

}
